#pragma once

#include "TcpConnect.h"
#include "Thread.h"
#include "ThreadPool.h"

#include <map>
#include <string>
#include <deque>

using namespace std;

class Server
{
public:
	Server(const string &name, const string &ip, const int port);
	
	virtual ~Server();
	
	int init();
	int run();
	int stop(){};
	int cleanup(){};
	
	bool started() const {return _started;}
	const string &getName() const {return _name;} 
	
	TcpThreadPool &getThreadPool(){return _threadPool;}

	void mutexLock(){pthread_mutex_lock(&_connectMapMutex);}
	void mutexUnLock(){pthread_mutex_unlock(&_connectMapMutex);}

	int resetConnect(int fd);
	int checkTask();
	TcpConnect* prepareConnect(int sockfd, Address &peerAddr);
	TcpConnect* getConnect(int fd);
private:
	string _name;
	bool _started;
	
	Address _listenAddr;
	int _listenSock;
	int _epfd;
	struct epoll_event _epevents[1024];
	struct epoll_event _eplistenevent;
	Thread _listenThread; //no in ThreadPool, for epoll

	int runInThread();

	TcpThreadPool _threadPool;
	
	map<int, TcpConnect *> _connectMap; //the Fd has been used

	
	pthread_mutex_t _connectMapMutex;
	pthread_cond_t _connectMapCond;
	
};

